package com.demo.mcp.server.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.autoconfigure.mcp.server.McpServerProperties;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

import java.net.URI;
import java.time.LocalDateTime;
import java.util.Map;

@Service
public class WeatherService {

    @Autowired
    private McpServerProperties mcpServerProperties;

    RestClient restClient = RestClient.create("https://api.vvhan.com") ;


    @Tool(description = "获取当前系统时间")
    public String getCurrentDateTime() {
        return LocalDateTime.now().atZone(LocaleContextHolder.getTimeZone().toZoneId()).toString();
    }

    @Tool(description = "根据经纬度获取天气预报")
    public String getWeatherForecastByLocation_(
            @ToolParam(description = "纬度，例如：39.9042") String latitude,
            @ToolParam(description = "经度，例如：116.4074") String longitude
    ) {
        return "当前位置（纬度：" + latitude + "，经度：" + longitude + "）的天气信息：天气很好，温度25°C";
    }

    @Tool(description = "根据城市名称获取天气预报")
    public String getWeatherByCity_32010(@ToolParam(description = "城市名称") String city) {
        System.err.printf("准备查询【%s】天气预报%n", city) ;
        Map<?, ?> result = restClient.get()
                .uri("/api/weather?city={0}", city)
                .retrieve()
                .body(Map.class) ;
        try {
            return new ObjectMapper().writeValueAsString(result);
        } catch (JsonProcessingException e) {
            return "获取天气信息失败：" + e.getMessage();
        }
    }

    @Tool(description = "获取IP地址详细信息")
    public String getIpAddressInfo_32010(@ToolParam(description = "IP地址") String ip) {
        System.err.printf("准备查询【%s】详细信息%n", ip) ;
        Map<?, ?> result = restClient.get()
                .uri("/api/ipInfo?ip={0}", ip)
                .retrieve()
                .body(Map.class) ;
        try {
            return new ObjectMapper().writeValueAsString(result) ;
        } catch (JsonProcessingException e) {
            return "获取IP地址详细信息失败：" + e.getMessage();
        }
    }


}
